/*
 * PesqUsuario.java
 *
 * Created on 03/12/2011, 17:51:23
 */
package telas.funcionarios;

import dao.FuncionarioDao;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import modelo.Funcionarios;
import telas.Index;

/**
 *
 * @author gilberto
 */
public class PesqFuncionario extends javax.swing.JFrame {

    List<Funcionarios> listaUsuarios = new ArrayList<Funcionarios>();
    List<Funcionarios> listaUsuariosTab = new ArrayList<Funcionarios>();

    public PesqFuncionario() {
        initComponents();
        jTextField1.requestFocus();
        listaUsuarios = FuncionarioDao.retornaUsuarios();
        listaUsuariosTab.addAll(listaUsuarios);
        adicionaFuncionarioTabela();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Nome busca");

        jTextField1.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                jTextField1CaretUpdate(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
        });

        jButton1.setText("Ok");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addGap(23, 23, 23))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 516, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-516)/2, (screenSize.height-337)/2, 516, 337);
    }// </editor-fold>//GEN-END:initComponents

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    this.dispose();
    Index.fr_usuario = null;
}//GEN-LAST:event_jButton2ActionPerformed

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
        if (jTable1.getRowCount() > 0) {
            jTable1.addRowSelectionInterval(0, 0);
            jTable1.requestFocus();
        }
    } else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
        dispose();
    } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        if (jTable1.getRowCount() == 1) {
            jTable1.addRowSelectionInterval(0, 0);
            jTable1.requestFocus();
            selecionaUsuario();
        } else if (jTable1.getRowCount() > 0) {
            jTable1.addRowSelectionInterval(0, 0);
            jTable1.requestFocus();
        }

    }
}//GEN-LAST:event_jTextField1KeyPressed

private void jTextField1CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jTextField1CaretUpdate
    listaUsuariosTab.removeAll(listaUsuariosTab);
    for (Funcionarios usu : listaUsuarios) {
        if (usu.getNome_func().toString().toUpperCase().contains(jTextField1.getText().toString().toUpperCase())
                || usu.getId_func().toString().toUpperCase().contains(jTextField1.getText().toString().toUpperCase())) {
            listaUsuariosTab.add(usu);
        }
    }
    adicionaFuncionarioTabela();
}//GEN-LAST:event_jTextField1CaretUpdate

private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        selecionaUsuario();
    } else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
        dispose();
    } else if (jTable1.getSelectedRow() == 0 && evt.getKeyCode() == KeyEvent.VK_UP) {
        jTextField1.requestFocus();
        jTextField1.selectAll();
    }
}//GEN-LAST:event_jTable1KeyPressed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    selecionaUsuario();
}//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PesqFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PesqFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PesqFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PesqFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PesqFuncionario().setVisible(true);
            }
        });
    }

    public final void adicionaFuncionarioTabela() {

        StringBuilder sb = new StringBuilder();
        Object colunas[] = {"Codigo", "Nome"};
        Object linhas[][] = {};
        DefaultTableModel modelos = new DefaultTableModel(linhas, colunas) {

            boolean[] canEdit = new boolean[]{
                false, false};

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        };

        if (listaUsuariosTab.isEmpty()) {
            //nenhum resultado
            int row = jTable1.getSelectedRow();
            JTable tabelas = new JTable(modelos);
            this.jTable1.setModel(tabelas.getModel());
            NumberFormat n = NumberFormat.getCurrencyInstance();

            // Código usado para dimensionar a largura da coluna
            jTable1.getColumnModel().getColumn(0).setPreferredWidth(60);
            jTable1.getColumnModel().getColumn(1).setPreferredWidth(400);
        } else {
            JTable tabelas = new JTable(modelos);
            while (modelos.getRowCount() > 0) {
                modelos.removeRow(0);
            }
            for (Funcionarios usu : listaUsuariosTab) {
                int row = jTable1.getSelectedRow();

                this.jTable1.setModel(tabelas.getModel());
                NumberFormat n = NumberFormat.getCurrencyInstance();
                // Adiciona uma linha
                SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
                modelos.addRow(new Object[]{usu.getId_func(), usu.getNome_func()});

                // Código usado para dimensionar a largura da coluna
                jTable1.getColumnModel().getColumn(0).setPreferredWidth(60);
                jTable1.getColumnModel().getColumn(1).setPreferredWidth(400);
                int qtd = jTable1.getRowCount();
                //coloca barra de rolagem na Horizontal
                jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            }
        }

    }

    public void selecionaUsuario() {
        if (jTable1.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(null, "Selecione um funcionário na tabela!");
        } else {
            Object xx = jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 0);//pego o codigo do cliente
            Long idUsuario = Long.parseLong(xx.toString());
            Fr_funcionario.populaCampos(idUsuario);
            dispose();
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
